<template>
  <div class="stats-panel">
    <!-- 图表标题 -->
    <div class="stats-panel-head">
      <h3>
        {{$t('common.customer.questionnaire.customerSatisfaction')}}
        <el-popover trigger="hover">
          <ul>
            <li> {{$t('report.customer.title18')}}</li>
          </ul>
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
    </div>
    <div class="stats-panel-body">
      <!-- 图表chart -->
      <div id="degree"></div>

      <!-- 列表标题&操作 -->
      <div class="stats-table-wrap" v-if="showTable">
        <div class="stats-table-header">
          <h3>{{ processTypeName ? `${processTypeName}${$t('common.base.list')}` : '' }}</h3>

          <el-button
            v-if="isShowRxportBtn"
            type="primary"
            @click="satisfactionGray ? exportData('single') : exportOldData()"
          >
          {{ $t('common.base.export') }}
          </el-button>
          <el-button
            v-if="isShowRxportBtn"
            type="primary"
            @click="satisfactionGray ? exportData('all') : exportOldAllData()"
          >
            {{ $t('common.base.exportAll') }}
          </el-button>
          <el-button type="primary" @click="showTable = false">
            {{ $t('common.base.collapse') }}
          </el-button>
        </div>

        <!-- 列表 -->
        <div>
          <el-table :data="page.list" class="stats-table">
            <el-table-column
              :label="$t('common.base.serialNumber')"
              prop="taskNo"
              width="150px"
              :show-overflow-tooltip="false"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="openDetail(scope.row)">
                  {{ scope.row.serialNumber }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              v-if="processType === 'TASK'"
              :label="$t('common.label.taskTemplate')"
              prop="templateName"
              width="120px"
            ></el-table-column>
            <el-table-column
              v-if="processType === 'EVENT'"
              :label="$t('common.label.eventType')"
              prop="templateName"
              width="120px"
            ></el-table-column>
            <el-table-column
              :label="$t('common.base.customer')"
              prop="customerName"
              min-width="120px"
            ></el-table-column>

            <el-table-column v-if="processType !== 'IM'" :label="$t('common.label.principalName')" width="120px">
              <template v-if="scope.row.executor" slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data
                    type="userName"
                    :openid="scope.row.executor.staffId"
                  ></open-data>
                </template>
                <template v-else>
                  {{ scope.row.executor.displayName }}
                </template>
              </template>
            </el-table-column>

            <el-table-column
              v-if="processType !== 'IM'"
              :label="$t('common.base.createUser')"
              prop="createUser"
              min-width="120px"
            >
              <template v-if="scope.row.createUser" slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data
                    type="userName"
                    :openid="scope.row.createUser.staffId"
                  ></open-data>
                </template>
                <template v-else>
                  {{ scope.row.createUser.displayName }}
                </template>
              </template>
            </el-table-column>

            <el-table-column
              v-if="processType == 'IM'"
              :label="$t('common.fields.customerServiceName.displayName')"
              prop="customerServiceName"
              min-width="120px"
            ></el-table-column>

            <el-table-column
              :label="$t('task.detail.components.evaluateTime')"
              prop="templateName"
              width="180px"
            >
              <template slot-scope="scope">
                {{ scope.row.reviewTime | fmt }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.base.degree')" prop="degree" width="100px"></el-table-column>
            <div v-if="notShowSatisfied">
              <template v-if="hasStar">
                <el-table-column v-for="(field, index) in evaluateConfig.starEvaluates" :label="field" :prop="`evaluateObj.${evaluateConfig.starEvaluateFeilds[index]}`" :key="field"/>
              </template>
              <el-table-column :label="$t('report.eventScoreChart.label1')" width="200px" prop="evaluateObj.tagEvaluates" show-overflow-tooltip v-if="hasTag">
                <template slot-scope="scope">{{scope.row.evaluateObj && scope.row.evaluateObj.tagEvaluates | prettyArray}}</template>
              </el-table-column>
              <el-table-column :label="$t('common.label.customerEvaluation')" width="240px" prop="evaluateContent" show-overflow-tooltip></el-table-column>
            </div>
            <el-table-column :label="$t('report.eventScoreChart.label2')" width="240px" prop="suggestion" show-overflow-tooltip></el-table-column>
          </el-table>

          <el-pagination
            class="stats-pagination"
            background
            @current-change="jump"
            :current-page="page.pageNum"
            layout="total, prev, pager, next"
            :total="page.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import Platform from '@src/platform'
import echarts from 'packages/Echarts';
import _ from 'lodash';
import { queryStatsCustomerList, satisfactionReportExport, checkSatisfactionGray, getReportAggregateAuth } from '@src/api/ReportApi.ts';
import http from '@src/util/HttpUtil'
import qs from '@src/util/querystring'
import { isEnterpriseEdition } from '@shb-lib/version';
import SampleTooltip from 'packages/SampleTooltip'
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
let degreeChart = null;
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { t } from '@src/locales';

export default {
  name: 'customer-degree-chart',
  props: {
    degreeData: Object,
    teamId: String,
    timeStart: Number,
    timeEnd: Number,
    evaluateConfig: Object,
    processType: String,
    processTypeName: String,
    chartType: String
  },
  data() {
    return {
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      showTable: false,

      model: {
        pageNum: 1,
        selectType: '',
      },
      page: {
        list: [],
      },
      isShowRxportBtn: false
    };
  },
  computed: {
    notShowSatisfied() {
      const RootWindow = getRootWindow(window);
      return !(isEnterpriseEdition()) && !(RootWindow?.grayAuth?.satisfaction);
    },
    hasStar(){
      return this.evaluateConfig.useStarEvaluate;
    },
    hasTag(){
      return this.evaluateConfig.useTagEvaluate;
    },
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'));
      return initData.auths?.EXPORT_IN || 0;
    },
    satisfactionGray() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.satisfaction;
    }
  },
  methods: {
    // 没有灰度还是走之前的接口
    exportOldData() {
      let model = {
        selectType: this.model.selectType,
        tagId: this.teamId
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      let url = '/api/report/outside/stats/customerTask/degree/export';
      if(this.processType === 'EVENT') {
        // 针对没有客户体验管理灰度并且选择了事件的导出
        url = '/api/report/outside/stats/customerEvent/degree/exportAll';
      }
      
      window.location.href = `${url}?${qs.stringify(model)}`;

      this.exportTrack(false)
    },
    exportOldAllData() {
      let model = {
        tagId: this.teamId
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      let url = '/api/report/outside/stats/customerTask/degree/exportAll';
      if(this.processType === 'EVENT') {
        // 针对没有客户体验管理灰度并且选择了事件的导出
        url = '/api/report/outside/stats/customerEvent/degree/exportAll';
      }
      
      window.location.href = `${url}?${ qs.stringify(model)}`;

      this.exportTrack(true)
    },
    // 导出数据 all/single
    async exportData(type) {
      const chartTotal = Object.values(this.degreeData).reduce((x, y) => x + y);
      let payload = {
        selectType: type === 'single' ? this.model.selectType : '',
        tags: this.teamId ? this.teamId.split(',') : [],
        type: this.processType,
        totalCount: type === 'single' ? this.page.total : chartTotal
      };

      if (this.timeStart) payload.timeStart = this.timeStart;
      if (this.timeEnd) payload.timeEnd = this.timeEnd;
      
      let { status, message } = await satisfactionReportExport(payload);
      this.$message({
        type:`${ status === 0 ? 'success' : 'error'}`,
        message
      });
      
      if(status === 0){
        window.parent.showExportList();
        window.parent.exportPopoverToggle(true);
      }

      this.exportTrack(type === 'all')
    },

    exportTrack(isExportAll) {
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.chartType
      }, '*')
    },

    // 打开工单详情
    openDetail(row) {
      const fromId = window.frameElement.getAttribute('id');
      let data = {}
      switch (this.processType) {
        case 'TASK':
          data = {
            type:PageRoutesTypeEnum.PageTaskView,
            key:row.id,
          }
          break;
        case 'EVENT':
          data = {
            type:PageRoutesTypeEnum.PageEventView,
            key:row.id,
          }
          break;
        case 'IM':
          data = {
            type:PageRoutesTypeEnum.PageImView,
            key:row.id,
          }
          break;
        default:
          break;
      }
      openAccurateTab({
        ...data,
        fromId,
        params:'noHistory=1'
      })
    },

    // 分页跳转
    jump(currentPage) {
      this.model.pageNum = currentPage;
      this.renderTable();
    },

    // 获取列表数据
    async fetchTableData() {
      let model = {
        pageNum: this.model.pageNum,
        selectType: this.model.selectType,
        type: this.processType,
        tags: this.teamId ? this.teamId.split(',') : [],
        pageSize: 10,
      };

      if (this.timeStart) model.timeStart = this.timeStart;
      if (this.timeEnd) model.timeEnd = this.timeEnd;

      const { result, success } = await queryStatsCustomerList(model);
      return success ? result : {};
    },

    // 渲染列表
    async renderTable() {
      let instance = this.$loading.show(this.$el);

      this.fetchTableData()
        .then(result => {
          this.page = result;
          this.showTable = true;
        })
        .catch(err => console.log(err))
        .finally(() => {
          instance.hide();
        });
    },

    // 渲染图表
    render() {
      degreeChart.clear();
      this.showTable = false;

      let option = this.getDegreeOption();
      degreeChart.setOption(option);
    },

    // 初始化图表
    initChart() {
      degreeChart = echarts.init(document.getElementById('degree'));
      window.addEventListener(
        'resize',
        _.debounce(function () {
          degreeChart.resize();
        }, 400)
      );

      degreeChart.on('click', event => {
        let name = event.name;
        let selectType = 'satisfaction';

        if (name == t('common.base.satisfactionDegree.2')) selectType = 'general';
        if (name == t('common.base.satisfactionDegree.3')) selectType = 'unSatisfaction';
        if (name == t('common.base.satisfactionDegree.0')) selectType = 'verySatisfaction';
        if (name == t('common.base.satisfactionDegree.4')) selectType = 'veryUnSatisfaction';

        this.model.selectType = selectType;
        this.model.pageNum = 1;
        this.renderTable();
      });

      this.render();
    },

    // 获取图表初始化配置
    getDegreeOption() {
      let legendData = [t('common.base.satisfactionDegree.0'), t('common.base.satisfactionDegree.1'), t('common.base.satisfactionDegree.2'), t('common.base.satisfactionDegree.3'), t('common.base.satisfactionDegree.4')];
      let data = this.degreeData || {};
      let pieData = [
        { name: t('common.base.satisfactionDegree.0'), value: data.verySatisfaction || 0 },
        { name: t('common.base.satisfactionDegree.1'), value: data.satisfaction || 0 },
        { name: t('common.base.satisfactionDegree.2'), value: data.general || 0 },
        { name: t('common.base.satisfactionDegree.3'), value: data.unSatisfaction || 0 },
        { name: t('common.base.satisfactionDegree.4'), value: data.veryUnSatisfaction || 0 },
      ];

      return {
        color: [this.getThemeColor, '#6da9e8', '#48e8ab', '#ffdd92', '#f6903d'],
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          top: 10,
          left: 10,
          data: legendData,
        },
        toolbox: {
          right: 40,
          top: 10,
          feature: {
            saveAsImage: {
              name: t('common.customer.questionnaire.customerSatisfaction')
            },
          },
        },
        series: [
          {
            name: t('common.base.degree'),
            type: 'pie',
            center: ['50%', '50%'],
            data: pieData,
            label: {
              normal: {
                formatter: '{b}： {c} ({d}%)',
              },
            },
            itemStyle: {
              normal: { label: { show: true } },
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      };
    },
    // 获取报表导出权限
    async getReportAggregateAuth(){
      try {
        const res = await getReportAggregateAuth();
        this.isShowRxportBtn = res?.auths?.REPORT_EXPORT ?? false;
      }catch(e) {
        console.log('getReportAggregateAuth: ', e)
      }
    },
  },
  mounted() {
    this.initChart();
    this.getReportAggregateAuth();
  },
  watch: {
    degreeData: {
      deep: true,
      handler(value) {
        this.render();
      },
    },
  },
  components: {
    [SampleTooltip.name]: SampleTooltip,
  },
};
</script>

<style lang="scss">
#degree {
  height: 480px;
  width: 100%;

  margin: 0 auto;
}
</style>
